package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 */
// 捕捉 加了RestController和Controller注解的类
@RestControllerAdvice(annotations = {Controller.class, RestController.class})
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 自定义业务异常处理器( LoginException)
     * @param le 异常对象
     * @return 返回异常信息
     */
    @ExceptionHandler(CustomException.class)
    public R<String> doLoginException(CustomException le){
        log.info("业务异常 : "+le.getMessage());
        return R.error(le.getMessage());
    }

    /**
     * 异常处理 sql异常
     * @param ex 异常对象
     * @return 异常信息
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> doException(SQLIntegrityConstraintViolationException ex){
        log.error("异常信息 :"+ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")){
            //截取动态异常信息
            String s = ex.getMessage().split(" ")[2];
            String msg = s + " 已存在";
            return R.error(msg);//返回异常信息
        }
        return R.error("未知错误");
    }
}
